package com.liu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.common.R;
import com.liu.entity.Category;
import com.liu.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜品分类管理
 */

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;


    /**
     * 新增菜品分类
     *
     * @param category
     * @return
     */
    @PostMapping()
    public R<String> save(@RequestBody Category category) {

        log.info("新增菜品分类：{}", category);

        // 调用service层方法保存分类信息
        categoryService.save(category);

        return R.success("新增菜品分类成功");
    }


    /**
     * 菜品分类分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getPage(int page, int pageSize) {

        // 创建分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);

        // 创建条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加排序条件
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort);

        // 执行分页查询
        categoryService.page(pageInfo, categoryLambdaQueryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 根据id删除菜品分类
     *
     * @param id
     * @return
     */
    @DeleteMapping()
    public R<String> delete(Long id) {

        categoryService.remove(id);

        return R.success("删除成功");
    }


    /**
     * 根据id修改菜品分类
     *
     * @param category
     * @return
     */
    @PutMapping()
    public R<String> update(@RequestBody Category category) {

        categoryService.updateById(category);

        return R.success("更新成功");
    }


    /**
     * 根据菜品条件查询菜品分类
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> getCategoryList(Category category) {

        // 创建条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        categoryLambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        // 添加排序条件
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        // 执行查询
        List<Category> categoryList = categoryService.list(categoryLambdaQueryWrapper);

        return R.success(categoryList);
    }

}
